<?php

namespace app\modules\api\controllers;

use yii\base\UserException;
use yii\rest\Controller;
use yii\web\Response;

/**
 * Default controller for the `api` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        return [
            'name' => \Yii::$app->name,
            'version' => \Yii::$app->version
        ];
    }

    public function actionUpload($id)
    {
        $data = \Yii::$app->wechat->downloadMedia($id);
        $downloadPath = __DIR__ . '/../../../web/uploads';
        $name = md5(microtime(true)) . '.jpg';
        $result = file_put_contents($downloadPath . '/' . $name, $data);
        if (!$result) {
            throw new UserException('上传失败，请重试');
        }
        \Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'url' => \Yii::$app->urlManager->createAbsoluteUrl(['/']) . 'uploads/' . $name
        ];
    }
}
